const express = require('express')
const app = express()
const db = require('../apis/connectMongo')

let userSchema = new db.Schema({
    name:         {type: String},
    username:     {type: String},
    password:     {type: String},
    icon:         {type: String},
    description:  {type: String, default: '该用户暂无个人描述'}
}, {collection: 'user'})       

let userModel = db.model('userModel', userSchema)

module.exports = {
  //  创建记录
  createUser: async (name, username, password, icon) => {
    try {
      await userModel.create({
        'name':     name,  
        'username': username,
        'password': password,
        'icon':     icon
      })
    } catch (err) {
      console.log(err)
    }
  },
  //  根据用户名查找记录
  findByUsername: async (username) => {
    try {
      let docs = await userModel.findOne({'username': username})
      return docs
    } catch (err) {
      console.log(err)
    }
  },
  //  根据昵称查找记录
  findByName: async (name) => {
    try {
      let docs = await userModel.findOne({'name': name})
      return docs
    } catch (err) {
      console.log(err)
    }
  },
  //  根据用户名和密码查找记录
  findByUsernameAndPassword: async (username, password) => {
    try {
      let docs = await userModel.findOne({
        'username': username,
        'password': password
      })
      return docs
    } catch (err) {
      console.log(err)
    }
  },
  //  获取8个用户
  findEightUser: async (username) => {
    try {
      let docs = await userModel.find({'username': {'$ne':username}}, null, {limit: 20} ,function(err, docs){ 
        if (err) console.log(err)
      })
      return docs
    } catch (err) {
      console.log(err)
    }
  },
  findAllUserNum: async () => {
    try {
      let docs = await userModel.find({})
      return docs.length
    } catch (err) {
      console.log(err)
    }
  },
  updateInfo: async (username, name, description, icon) => {
    try {
      await userModel.updateOne({
        'username': username
      }, {
        $set: {
          'name': name,
          'description': description,
          'icon': icon
        }
      })
    } catch (err) {
      console.log(err)
    }
  }
}